﻿Imports open = OpenNETCF.Desktop.Communication
Imports System.IO
Imports Msg = 掃描系統.scanMsg

Public Class CasioOperate

#Region " variable "

    Dim rapi As open.RAPI

    ''' <summary>
    ''' 是否获取到了Casio编号配置信息
    ''' </summary>
    Private _hasconfig As Boolean = False
    Public ReadOnly Property Hasconfig() As Boolean
        Get
            Return _hasconfig
        End Get
    End Property



    Dim dotFomart As String = String.Empty
    ''' <summary>
    ''' Casio的编号
    ''' </summary>
    ''' <remarks></remarks>
    Private casioID As String = String.Empty
    ''' <summary>
    '''Casio中的配置文件名稱 
    ''' </summary>
    Dim casioConfigfile As String = "\windows\sys_workStation.txt"
    ''' <summary>
    '''用于設置Casio配置文件（中轉作用），還不能直接讀取Casio的文件內容
    ''' </summary>
    Dim localconfig As String = System.IO.Path.Combine(Application.StartupPath, "casioconfig.txt")

    ''' <summary>
    '''连接的状态 
    ''' </summary>
    ''' <remarks></remarks>
    Public Enum Adtion
        ''' <summary>
        ''' 没有安装ActiveSync
        ''' </summary>
        ''' <remarks></remarks>
        NoActiveSync1
        ''' <summary>
        ''' 没有连接
        ''' </summary>
        ''' <remarks></remarks>
        UnConnected2
        ''' <summary>
        ''' 连接失败
        ''' </summary>
        ''' <remarks></remarks>
        ''' 
        ConnectFailed3
        ''' <summary>
        ''' 连接成功
        ''' </summary>
        ''' <remarks></remarks>
        Connected3
        ''' <summary>
        ''' 连接成功但是没有配置文件（CasioID）
        ''' </summary>
        ''' <remarks></remarks>
        Connected_NoCfgFile4
        ''' <summary>
        ''' 连接成功且含有配置文件（CasioID）
        ''' </summary>
        ''' <remarks></remarks>
        Connected_HaveCfgFile5
        ''' <summary>
        ''' 连接成功没有有效的配置信息（CasioID）
        ''' </summary>
        ''' <remarks></remarks>
        Connected_NotValidCfg6
        ''' <summary>
        ''' 连接成功，含有有效的配置信息（CasioID）
        ''' </summary>
        ''' <remarks></remarks>
        Connected_ValidCfg7
    End Enum

    ''' <summary>
    ''' 當前的情況
    ''' </summary>
    ''' <remarks></remarks>
    Private _stationAdtion As Adtion


#End Region

    Private Function CheckActiveSync(Optional ByVal showMsg As Boolean = False) As Boolean
        Dim rapidll As String = Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.System), "rapi.dll")
        Dim have As Boolean = False
        If (File.Exists(rapidll) = False) Then
            If (showMsg = True) Then
                msg.MsgError("檢測不到ActiveSync軟體", "错误")
            End If
            _stationAdtion = Adtion.NoActiveSync1
            have = False
            Exit Function
        Else
            have = True
            _stationAdtion = Adtion.UnConnected2
        End If
        Return have
    End Function

    ''' <summary>
    ''' 获取當前的状态情況
    ''' </summary>
    ''' <remarks></remarks>
    Public ReadOnly Property StationAdtion() As Adtion
        Get
            Return _stationAdtion
        End Get
    End Property

    Public Sub New()
        If (Me.CheckActiveSync() = False) Then
            Exit Sub
        End If
        Try
            rapi = New open.RAPI()
        Catch ex As Exception
            _stationAdtion = Adtion.NoActiveSync1
            Exit Try
            Exit Sub
        End Try
        Me.PrepareRapi(True, 1)

        casioID = Me.getconfig()
        If String.IsNullOrEmpty(casioID) = True Then
            Exit Sub
        End If
        dotFomart = "-" + casioID + "."
    End Sub

    ''' <summary>
    ''' 在PC上獲取CasioUUID編號，Casio供應商寫在ROM中的編號
    ''' </summary>
    ''' <returns>不成功則返回空字符串——""</returns>
    ''' <remarks></remarks>
    Public Function GetCasioUUID() As String
        Dim CasioUUID As String = String.Empty

        Dim appPath As String = Application.StartupPath
        If (rapi.DeviceFileExists("\windows\SystemLibNet.dll") = False) Then
            Dim sysfile As String = Path.Combine(appPath, "Tools\SystemLibNet.dll")
            If File.Exists(sysfile) = False Then
                msg.MsgError("找不到文件" + sysfile, "错误")
                Return CasioUUID
            End If
            rapi.CopyFileToDevice(sysfile, "\windows\SystemLibNet.dll")
        End If

        Dim CasioIDFile As String = Path.Combine(rapi.GetDeviceSystemFolderPath(OpenNETCF.Desktop.Communication.SystemFolders.Personal), "ID.txt")
        Dim PCCasioIDFile As String = Path.Combine(appPath, "CasioID.txt")
        Dim GetIDProgram As String = Path.Combine(appPath, "Tools\KaronID.exe")

        If (File.Exists(GetIDProgram)) Then
            rapi.CopyFileToDevice(GetIDProgram, "\windows\KaronID.exe", True)
        Else
            MessageBox.Show("找不到文件" + GetIDProgram, "", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
            Return CasioUUID
        End If

        If (rapi.DeviceFileExists("\windows\KaronID.exe")) Then
            rapi.CreateProcess("\windows\KaronID.exe", "ExcuteNoNotes")
        End If

        If (rapi.DeviceFileExists(CasioIDFile)) Then
            rapi.CopyFileFromDevice(PCCasioIDFile, CasioIDFile, True)
            If (File.Exists(PCCasioIDFile)) Then
                CasioUUID = File.ReadAllText(PCCasioIDFile).Trim()
            End If
        End If
        Return CasioUUID
    End Function

    ''' <summary>
    ''' 每次使用完成后必須調用，以釋放資源
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Close()
        rapi.Dispose()
    End Sub

    Public Sub CreateDevicePath(ByVal path As String)
        rapi.CreateDeviceDirectory(path)
    End Sub

    ''' <summary>
    ''' 是否存在指定的文件或者目錄
    ''' </summary>
    ''' <param name="path">設備上的文件或者目錄的完整路徑</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ExistsDevicePath(ByVal path As String) As Boolean
        Return rapi.DeviceFileExists(path)
    End Function

    Public Enum PCPathMode
        CasioToPC
        PCToCasio
    End Enum

    ''' <summary>
    ''' 獲取PC上的路徑
    ''' </summary>
    ''' <remarks></remarks>
    Public Function getPCPath(ByVal pcPathMode As PCPathMode) As String
        Dim pcpath As String = String.Empty
        Dim tb As System.Data.DataTable
        Dim sql As String = String.Empty
        If (pcPathMode = CasioOperate.PCPathMode.CasioToPC) Then
            sql = "select listA,* from dbo.BSC_OtherDefineB where itemno=94 and listcode='xmlpathUp'"
        ElseIf (pcPathMode = CasioOperate.PCPathMode.PCToCasio) Then
            sql = "select listA,* from dbo.BSC_OtherDefineB where itemno=94 and listcode='xmlpathDown'"
        End If
        tb = Exec(sql, E_ExecType.DataTable)
        If (tb.Columns.Count > 0) Then
            If tb.Rows(0)(0) Is GetType(System.DBNull) Then
            Else
                pcpath = Convert.ToString(tb.Rows(0)(0))
            End If
        End If
        Return pcpath
    End Function


    Public Function Upload(ByVal reconnect As Boolean, ByVal PCpath As String, ByVal CasioFileName As String) As Boolean
        Dim succed As Boolean = False
        If (PrepareRapi(reconnect, 1)) Then
            Dim files As open.FileList = rapi.EnumFiles(CasioFileName)
            Dim casioPath = Path.GetDirectoryName(CasioFileName)
            Dim PCfile As String
            Dim casiofile As String
            Dim pcname As String
            For Each file As open.FileInformation In files
                ''设置文件名
                ''对文件夹不做处理
                If Not Path.HasExtension(file.FileName) Then
                    Continue For
                End If
                pcname = file.FileName.Replace(".", dotFomart)
                PCfile = Path.Combine(PCpath, pcname)
                casiofile = Path.Combine(casioPath, file.FileName)
                rapi.CopyFileFromDevice(PCfile, casiofile, True)
            Next
            succed = True
        End If
        Return succed
    End Function

    ''' <summary>
    ''' “ 上傳文件到電腦的目錄 ”
    ''' </summary>
    ''' <param name="PCpath" >要上傳到電腦的目錄（本機或者遠程的共享目錄）</param>
    ''' <param name="CasioFileName">Casio中的文件名（egg.  "\scan\data\*.*" ）</param>
    ''' <returns>上傳是否成功</returns>
    Public Function Upload(ByVal PCpath As String, ByVal CasioFileName As String) As Boolean
        Me.Upload(False, PCpath, CasioFileName)
    End Function

    ''' <summary>
    ''' " 下载电脑文件到Casio指定路徑 "
    ''' </summary>
    ''' <param name="PCfile"></param>
    ''' <param name="Casiopath"></param>
    Public Function DownloadFile(ByVal PCfile As String, ByVal Casiopath As String) As Boolean
        Dim succed As Boolean = False
        If (IfConnected() = True) Then
            Dim PCPath As String = Path.GetDirectoryName(PCfile)
            If PCfile.Contains(dotFomart) Then
                Dim casiofilename As String = Path.GetFileName(PCfile).Replace(dotFomart, ".")
                Dim casiofile As String = Path.Combine(Casiopath, casiofilename)
                rapi.CopyFileToDevice(PCfile, casiofile, True)
                succed = True
            End If
        End If
        Return succed
    End Function


    ''' <summary>
    ''' " 下載電腦的文件夾到Casio指定路徑 "
    ''' </summary>
    ''' <param name="CasioPath" >必须是文件夾路径形式</param>
    ''' <param name="PCPath" >必须是文件夾路径形式</param>
    Public Function Download(ByVal PCPath As String, ByVal CasioPath As String) As Boolean
        Dim succed As Boolean = False
        If (IfConnected() = True) Then
            Dim files As String() = System.IO.Directory.GetFiles(PCPath)
            Dim remotefile As String
            Dim localfile As String
            Dim casiofilename As String = String.Empty
            For Each file As String In files
                If file.Contains(dotFomart) Then
                    localfile = Path.Combine(PCPath, file)
                    casiofilename = Path.GetFileName(file).Replace(dotFomart, ".")
                    remotefile = Path.Combine(CasioPath, casiofilename)
                    rapi.CopyFileToDevice(localfile, remotefile, True)
                End If
            Next
            succed = True
        End If
        Return succed
    End Function


    ''' <summary>
    ''' “ 用于連接Casio設備 ”
    ''' </summary>
    ''' <param name="ifconnect" >如果沒有連接，是否要連接</param>
    ''' <param name="TimeoutSeconds">設置超時的時間（秒）</param>
    ''' <returns>連接是否成功</returns>
    Private Function PrepareRapi(ByVal ifconnect As Boolean, ByVal TimeoutSeconds As Int32) As Boolean
        Dim succed As Boolean = False

        If (ifconnect = True) Then
            If Me.CheckActiveSync(True) = False Then
                Return succed
            End If
        End If

        If (rapi.Connected = False And ifconnect = True) Then
            Try
                rapi.Connect(False, TimeoutSeconds)
                System.Threading.Thread.Sleep(500)
            Catch ex As open.RAPIException
                MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1)
            End Try
        End If
        succed = rapi.Connected
        If (succed = False And ifconnect = True) Then
            _stationAdtion = Adtion.ConnectFailed3
            ''MessageBox.Show("連接失敗，請確認Casio已經成功連接到電腦")
        ElseIf (succed = True) Then
            _stationAdtion = Adtion.Connected3
        End If
        Return succed
    End Function

    Public Function IfConnected() As Boolean
        Return PrepareRapi(False, 1)
    End Function

    Public Sub setConfigFile(ByVal workstation As String)
        If (IfConnected() = True) Then
            Dim sw As New StreamWriter(Me.localconfig, False, System.Text.Encoding.Unicode)
            sw.WriteLine("workStation=" + workstation)
            sw.Close()
            If rapi.DeviceFileExists(casioConfigfile) Then
                If (msg.MsgYesNo("檔案已經存在，是否要刪除", "確認刪除檔案") = DialogResult.Yes) Then
                    rapi.DeleteDeviceFile(casioConfigfile)
                    rapi.CopyFileToDevice(localconfig, casioConfigfile)
                Else
                    Exit Sub
                End If
            End If
        End If
    End Sub

    ''' <summary>
    '''Casio上是否有配置文件，有則獲取該文件到本地文件 
    ''' </summary>
    Private Function getconfigfile() As Boolean
        Dim have As Boolean = False
        If (IfConnected() = True) Then
            If (rapi.DeviceFileExists(casioConfigfile)) Then
                rapi.CopyFileFromDevice(localconfig, casioConfigfile, True)
                have = True
                _stationAdtion = Adtion.Connected_HaveCfgFile5
            Else
                have = False
                _stationAdtion = Adtion.Connected_NoCfgFile4
            End If
        End If
        Return have
    End Function


    ''' <summary>
    ''' 获取Casio的编号信息
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function getconfig() As String
        Dim workstation As String = String.Empty
        If (getconfigfile() = True) Then
            Dim sr As New StreamReader(Me.localconfig, True)
            Dim line As String = sr.ReadLine()
            sr.Close()
            If line.Contains("=") Then
                Dim parts As String() = line.Split("=")
                If parts.Length <> 2 Then
                    _stationAdtion = Adtion.Connected_NotValidCfg6
                    MessageBox.Show("找不到Casio编号的配置信息")
                    workstation = ""
                    Me._hasconfig = False
                Else
                    If parts(0).Equals("workstation", StringComparison.InvariantCultureIgnoreCase) = False Then
                        _stationAdtion = Adtion.Connected_NotValidCfg6
                        MessageBox.Show("找不到Casio编号的配置信息")
                        workstation = ""
                        Me._hasconfig = False
                    Else
                        workstation = parts(1).Trim()
                        _stationAdtion = Adtion.Connected_ValidCfg7
                        Me._hasconfig = True
                    End If
                End If
            End If
        ElseIf (_stationAdtion = Adtion.Connected_NoCfgFile4) Then
            MessageBox.Show("找不到Casio编号的配置文件")
        End If
        Return workstation
    End Function

    ''' <summary>
    ''' 在設備的桌面創建快捷方式
    ''' </summary>
    ''' <param name="shortCutName">快捷方式顯示的名稱</param>
    ''' <param name="Target">快捷方式所指向的路徑，如“\Karon\CF.exe”</param>
    ''' <remarks></remarks>
    Public Sub CreateDeviceShortCut(ByVal shortCutName As String, ByVal Target As String)
        If (Me.IfConnected()) Then
            Dim desktoppath As String = rapi.GetDeviceSystemFolderPath(open.SystemFolders.Desktop)
            Dim name As String = Path.Combine(desktoppath, shortCutName + ".lnk")
            If (rapi.DeviceFileExists(name)) Then
                rapi.DeleteDeviceFile(name)
            End If
            rapi.CreateDeviceShortcut(shortCutName, Target)
        End If
    End Sub

    ''' <summary>
    '''创建Casio中的ActiveSync连接程式的快捷方式
    ''' </summary>
    ''' <remarks></remarks>
    Public Function CreateConnectLink() As Boolean
        Dim succed As Boolean = False
        If (Me.IfConnected()) Then
            Dim name As String = Path.Combine("\windows", "repllog.lnk")
            Dim desktoppath As String = rapi.GetDeviceSystemFolderPath(open.SystemFolders.Desktop)
            Dim name2 As String = Path.Combine(desktoppath, "Connect.lnk")
            If Not rapi.DeviceFileExists(name2) And rapi.DeviceFileExists(name) Then
                rapi.CopyFileOnDevice(name, name2)
                rapi.SetDeviceFileAttributes(name2, OpenNETCF.Desktop.Communication.RAPI.RAPIFileAttributes.Normal)
                succed = True
            End If
        Else
            succed = False
        End If
        Return succed
    End Function
End Class
